package srw;

import java.util.List;
import java.util.Vector;

import LexParser.LexParser;

/**
 * 
 * Main algorithm, first vercion
 * builds the result tree in a top-down way
 * 
 */

public class SentenceTreeBuilder {

	private LexParser _lexParser;
	private TreeFoundListerer _listener;
	private Vector<String> _sentenceWords = new Vector<String>();
	private Vector<TreeArgument> _arguments = new Vector<TreeArgument>();
	private WordTreeNode _rootNode;
	
	public SentenceTreeBuilder(LexParser lexParser) {
		_lexParser = lexParser;
	}

	public void buildTree () {
		
		System.err.println("BUILD SENTENCE TREE");
		_rootNode = new WordTreeNode(null, Word.UNIVERSAL_WORD);
		_arguments.add(new TreeArgument (Argument.UNIVERSAL_ARGUMENT, _rootNode, 0));
		
		addNode(_sentenceWords);
	}
	
	private void addNode (Vector<String> sentence) {
		if (_arguments.isEmpty()) {
			if (sentence.isEmpty()) {
				_listener.treeFound(_rootNode);
			}
			return;
		}
			
		TreeArgument argument = _arguments.remove(0);
		 
		for (String string : sentence) {
//			Vector<Word> words = Dictionary.instance().getWords(string);
			List<Word> words = _lexParser.getWords(string);
			if (words == null || words.isEmpty()) {
				_listener.incorrectInput(string);
				return;
			}
			
			for (Word word : words) {
				if (argument.accepts(word.getProperties())) {
					WordTreeNode parent = argument.getTreeNode();
					WordTreeNode child = new WordTreeNode(parent, word);
					parent.setChild(child, argument.getNumber());
					Vector<String> newSentence = new Vector<String>(sentence);
					newSentence.remove(string);
					Vector<Argument> childArgs = word.getArguments();
					Vector<TreeArgument> childTreeArgs = new Vector<TreeArgument>(); 
					for (int i = 0; i < childArgs.size(); i++) {
						childTreeArgs.add(new TreeArgument(childArgs.elementAt(i), child, i));
					}
					_arguments.addAll(childTreeArgs);
					addNode(newSentence);
					_arguments.removeAll(childTreeArgs);
				}
			}
		}
		
		_arguments.add(argument);
		
	}
	
	public void setSentenceWords(Vector<String> sentenceWords) {
		_arguments.clear();
		_sentenceWords = sentenceWords;
	}

	public void setListener(TreeFoundListerer listener) {
		_listener = listener;
	}
	
}
